package com.china.springServer.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * @fileName: ThreadPoolService
 * @author: LmR
 * @createDate: 2023/10/22 9:13
 * @Desc:
 */
@Component
public class ThreadPoolService {

    @Autowired
    private ExecutorService customerThreadPool;

    @Autowired
    private List<Callable<String>> taskList;

    @Async(value = "myDefaultThreadPool")
    public void task() {
        System.out.println("当前线程为:" + Thread.currentThread());
    }

    public void batchTaskExecute() {
        for (int i = 0; i < 10; i++) {
            customerThreadPool.execute(() -> {
                System.out.println("当前线程:" + Thread.currentThread());
                try {
                    Thread.sleep(2000);
                } catch (Exception e) {
                }
            });
        }
    }

    public void batchTaskSubmit() {
        for (int i = 0; i < 10; i++) {
            customerThreadPool.submit(() -> {
                System.out.println("当前线程:" + Thread.currentThread());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            });
        }
    }

    public void batchTaskListSubmit() {
        List<Future<String>> results = new ArrayList<>();
        for (Callable<String> callable : taskList) {
            results.add(customerThreadPool.submit(callable));
        }
        for (Future<String> result : results) {
            try {
                System.out.println(result.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        System.out.println("batch task completed!!!");
    }
}
